<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">系统通知</div>
        <div class="flex">
          <el-button
            type="primary"
            v-if="has_role_list[3].has_role"
            @click="
              ;(show_box = true),
                (param_list = [
                  {
                    url: '',
                    param_arguments_list: [{ ...param_list_item }],
                  },
                ])
            "
            >新增</el-button
          >

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <myTable
        :data="list"
        :maxHeight="max_height"
        :height_size="height_size"
        :loading="loading"
        :header_list="header_list"
        @edit_list="edit_list"
      ></myTable>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="70%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(addsysnoticeform)"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增系统消息</h4>
        <h4 v-else>编辑系统消息</h4>
      </template>
      <template #default>
        <el-form
          ref="addsysnoticeform"
          :model="add_form_data"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="通知标题" prop="title">
            <el-input v-model="add_form_data.title" placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="add_form_data.type"
              @change="
                ;(receiveMemberIdList = []), (receiveEnterpriseIdList = [])
              "
            >
              <el-option
                v-for="item in type_list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="特定用户" v-if="add_form_data.type == '2'">
            <el-select
              style="width: 100%"
              v-model="receiveMemberIdList"
              multiple
              remote-show-suffix
              filterable
              remote
              placeholder="请选择"
            >
              <el-option
                v-for="item in member_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="特定企业用户" v-if="add_form_data.type == '3'">
            <el-select
              style="width: 100%"
              v-model="receiveEnterpriseIdList"
              multiple
              filterable
              remote-show-suffix
              remote
              placeholder="请选择"
            >
              <el-option
                v-for="item in enterprise_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="特殊场景">
            <el-radio v-model="add_form_data.isSpecScene" :label="true"
              >是</el-radio
            >
            <el-radio v-model="add_form_data.isSpecScene" :label="false"
              >否</el-radio
            >
          </el-form-item>
          <el-form-item label="场景类型">
            <el-select v-model="add_form_data.sceneType">
              <el-option
                v-for="item in scene_type_list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="add_form_data.startTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择"
              @change="add_form_data.endTime = ''"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="add_form_data.endTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择"
              :disabled-date="disabledEndTime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="进入url地址">
            <el-table :data="param_list" border class="tc url_table">
              <el-table-column label="url地址">
                <template #default="scope: any">
                  <el-form-item prop="url" style="padding: 20px 0">
                    <el-input
                      v-model="scope.row.url"
                      placeholder="请输入"
                      prop="requiredUrl"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="参数(键值对<均不可为空>)">
                <template #default="scope: any">
                  <div
                    class="flex p_5"
                    v-for="(item, index) in scope.row.param_arguments_list"
                  >
                    <el-input
                      style="width: 180px"
                      v-model="item[0]"
                      placeholder="请输入键"
                    ></el-input>
                    <span class="m_0_10">-</span>
                    <el-input
                      style="width: 180px"
                      v-model="item[1]"
                      placeholder="请输入值"
                    ></el-input>
                    <el-button
                      class="m_left10"
                      @click="
                        add_param_item({
                          list_index: scope.$index,
                          param_index: index,
                          type: 1,
                        })
                      "
                      >追加列</el-button
                    >
                    <el-button
                      @click="
                        add_param_item({
                          list_index: scope.$index,
                          param_index: index,
                          type: 2,
                        })
                      "
                      v-show="index > 0"
                      >删除列</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="m_top10">
              <el-button type="primary" @click="add_params_list(1)"
                >追加一行</el-button
              >
              <el-button
                type="primary"
                @click="add_params_list(2)"
                v-if="param_list.length > 1"
                >删除最后一行</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="跳转url地址">
            <el-input v-model="add_form_data.jumpUrl" placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item label="最大发送次数">
            <el-input
              v-model="add_form_data.maxTimes"
              placeholder="请输入（默认不限次数）"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="消息内容">
            <wangeditor
              :text="add_form_data.content"
              style="height: 500px"
            ></wangeditor>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addsysnoticeform)">取消</el-button>
            <el-button
              type="primary"
              @click="submit_form(addsysnoticeform)"
              :loading="btn_loading"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { formatDate, debounce, check_role } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import table_edit from '@/view/components/table_edit.vue' // 列表操作图标 （含权限）
import myTable from '@/view/components/myTable.vue'
import { onMounted, ref, reactive, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import wangeditor from '@/view/components/wangeditor.vue'
import { FormInstance, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import { useStore } from 'vuex'
const store = useStore()
// type FormInstance = InstanceType<typeof ElForm>
const addsysnoticeform = ref<FormInstance>()
const requiredUrl = (rule: any, value: any, callback: any) => {
  if (param_list.value.length == 1 && param_list.value[0].url == '') {
    return callback(new Error('请至少填写一行地址栏'))
  } else {
    callback()
  }
}
const has_role_list = ref([
  {
    path: 'sysNotice/status',
    has_role: false,
  },
  {
    path: 'sysNotice/put',
    has_role: false,
  },
  {
    path: 'sysNotice/delete',
    has_role: false,
  },
  {
    path: 'sysNotice/post',
    has_role: false,
  },
])
const rules = reactive<FormRules>({
  url: [{ validator: requiredUrl }],
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
})
const disabledEndTime = (time) => {
  return (
    time.getTime() < add_form_data.value.startTime + 3600 * 1000 * 24 ||
    time.getTime() < new Date()
  )
}
const list = ref()
const total = ref()
const max_height = ref()
const show_box = ref()
const loading = ref(false)
const height_size = ref(1)
const type_list = ref([
  { value: '1', label: '所有用户' },
  { value: '2', label: '特定用户' },
  { value: '3', label: '特定企业用户' },
])
const scene_type_list = ref([
  { value: '1', label: '通用' },
  { value: '2', label: '铝膜设计' },
  { value: '3', label: '数字孪生' },
  { value: '4', label: '成功登录' },
])
const header_list = ref<any>([
  {
    label: '标题',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
    prop: 'title',
  },
  {
    label: '类型',
    value: '',
    showTable: true,
    type: 'select',
    isShow: true,
    options: type_list.value,
    prop: 'type',
  },
  {
    label: '特殊场景',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: '1',
        label: '是',
      },
      {
        value: '0',
        label: '否',
      },
    ],
    prop: 'isSpecScene',
  },
  {
    label: '场景类型',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: scene_type_list.value,
    prop: 'sceneType',
  },
  {
    label: '开始时间',
    value: '',
    showTable: true,
    type: 'dateDay',
    isShow: false,
    options: [],
    prop: 'startTime',
    is_time_stamp: true,
  },
  {
    label: '结束时间',
    value: '',
    showTable: true,
    type: 'dateDay',
    isShow: false,
    options: [],
    prop: 'endTime',
    is_time_stamp: true,
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: '1',
        label: '启用',
      },
      {
        value: '0',
        label: '停用',
      },
    ],
    prop: 'status',
  },
  {
    label: '最大发送次数',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'maxTimes',
  },
])

const page_data = ref({
  current: 1,
  pageSize: 10,
  type: '',
  isSpecScene: '',
  sceneType: '',
  status: '',
  maxTimes: '',
  startTime: '',
  endTime: '',
  title: '',
})
const receiveEnterpriseIdList = ref([])
const enterprise_list = computed(() => {
  return store.state.enterprise_list
})
const receiveMemberIdList = ref([])
const member_list = ref()
const get_member_list = () => {
  axios
    .request({
      url: serviceApi.platform_member_list,
      method: 'post',
      data: { current: 1, pageSize: 10000 },
    })
    .then((res) => {
      member_list.value = res.data.content
    })
}
const param_list_item = ref(['', ''])
const param_list = ref([])
const add_form_data = ref({
  title: '',
  id: '',
  content: '',
  endTime: '',
  jumpUrl: '',
  maxTimes: '',
  noticeReceiveList: [],
  isSpecScene: true,
  sceneType: '1',
  startTime: '',
  status: true,
  type: '1',
  url: [],
})
onMounted(() => {
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('操作成功！')
  })
  EventBus.on('commit_editor', (e) => {
    add_form_data.value.content = e as any
    if (e == '' || e == '<p><br></p>') {
      btn_loading.value = false
      ElMessage.error('消息内容不能为空!')
      return
    }
    add_submit()
  })
  get_list()
  get_member_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
  EventBus.off('commit_editor')
})
const btn_loading = ref(false)
const add_submit = () => {
  axios
    .request({
      url:
        add_form_data.value.id == ''
          ? serviceApi.notice_crud
          : serviceApi.notice_crud + '/' + add_form_data.value.id,
      method: add_form_data.value.id == '' ? 'post' : 'put',
      data: add_form_data.value,
    })
    .then((res) => {
      console.log(res)
      ElMessage.success('操作成功！')
      setTimeout(() => {
        btn_loading.value = false
        show_box.value = false
        resetForm(addsysnoticeform.value)
        get_list()
      }, 1000)
    })
    .catch((err) => {
      btn_loading.value = false
      ElMessage.error(err)
    })
}
const add_param_item = (e) => {
  if (e.type == 1) {
    if (
      param_list.value[e.list_index].param_arguments_list.at(-1)[0] == '' ||
      param_list.value[e.list_index].param_arguments_list.at(-1)[1] == ''
    ) {
      ElMessage.error('请优先完善空白键值对信息')
      return
    }
    param_list.value[e.list_index].param_arguments_list.push({
      ...param_list_item.value,
    })
  } else {
    param_list.value[e.list_index].param_arguments_list.splice(e.param_index, 1)
  }
}
const add_params_list = (e) => {
  if (e == 1) {
    if (param_list.value.at(-1).url == '') {
      ElMessage.error('请优先完善空白地址栏信息')
      return
    }
    param_list.value.push({
      url: '',
      param_arguments_list: [{ ...param_list_item.value }],
    })
  } else {
    param_list.value.splice(param_list.value.length - 1, 1)
  }
}
const submit_form = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      let dataUrlList = JSON.parse(JSON.stringify(param_list.value))
      dataUrlList.forEach((item) => {
        item.param_arguments_list = item.param_arguments_list.filter(
          (item1) => {
            return item1[0] != '' && item1[1] != ''
          }
        )
        if (item.param_arguments_list.length) {
          item = Object.assign(item, {
            param: Object.fromEntries(item.param_arguments_list),
          })
        }
        delete item.param_arguments_list
      })
      add_form_data.value.url = dataUrlList
      if (add_form_data.value.type == '2') {
        receiveMemberIdList.value.forEach((item) => {
          let obj_item = {
            receiveMemberId: item,
          }
          add_form_data.value.noticeReceiveList.push(obj_item)
        })
      }
      if (add_form_data.value.type == '3') {
        receiveEnterpriseIdList.value.forEach((item) => {
          let obj_item = {
            receiveEnterpriseId: item,
          }
          add_form_data.value.noticeReceiveList.push(obj_item)
        })
      }
      console.log(add_form_data.value)
      add_form_data.value.maxTimes =
        add_form_data.value.maxTimes == '' ? '0' : add_form_data.value.maxTimes
      EventBus.emit('submit')
    }
  })
}
const edit_list = (e) => {
  if (e.type == 1 || e.type == 2) {
    if (
      !e.item.status &&
      e.item.endTime !== null &&
      e.item.endTime <= new Date()
    ) {
      ElMessage.error('已到达结束日期，不可再启用')
      return
    }
    ElMessageBox.confirm(
      e.item.status ? '确定停用该记录？' : '确定启用该记录？',
      '',
      {
        closeOnClickModal: false,
        type: 'warning',
      }
    )
      .then(() => {
        axios
          .request({
            url:
              serviceApi.notice_status + '/' + e.item.id + '/' + !e.item.status,
            method: 'put',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((error) => {
            ElMessage.error(error)
          })
      })
      .catch(() => {})
  } else if (e.type == 3) {
    update_list(e.item)
  } else {
    ElMessageBox.confirm('确定删除该记录？', '', {
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.notice_crud + '/' + e.item.id,
            method: 'delete',
          })
          .then(() => {
            ElMessage.success('删除成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((error) => {
            ElMessage.error(error)
          })
      })
      .catch(() => {})
  }
}
const update_list = (e) => {
  add_form_data.value = {
    id: e.id,
    title: e.title ? e.title : '',
    content: e.content,
    endTime: parseInt(e.endTime) as any,
    jumpUrl: e.jumpUrl,
    maxTimes: e.maxTimes == 0 ? '' : e.maxTimes,
    noticeReceiveList: [],
    sceneType: e.sceneType + '',
    isSpecScene: e.isSpecScene,
    startTime: parseInt(e.startTime) as any,
    status: e.status,
    type: e.type + '',
    url: [],
  }
  console.log(JSON.parse(e.url))
  if (e.type == 2) {
    e.noticeReceiveList.forEach((item) => {
      receiveMemberIdList.value.push(item?.receiveMemberId)
    })
  }
  if (e.type == 3) {
    e.noticeReceiveList.forEach((item) => {
      receiveEnterpriseIdList.value.push(item?.receiveEnterpriseId)
    })
  }
  let data = JSON.parse(e.url)
  data.forEach((item) => {
    let param_item = {
      url: item.url,
      param_arguments_list: item.param
        ? Object.entries(item.param)
        : [{ ...param_list_item.value }],
    }
    param_list.value.push(param_item)
  })
  console.log(param_list.value)
  show_box.value = true
}
const get_list = () => {
  axios
    .request({
      url: serviceApi.notice_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      if (res.data === null) return
      res.data.content.forEach((i) => {
        i.btn_list = [
          {
            label: '禁用',
            icon: 'table_status_enable',
            has_role: has_role_list.value[0].has_role,
            btn_show: i.status,
          },
          {
            label: '启用',
            icon: 'table_status_disable',
            has_role: has_role_list.value[0].has_role,
            btn_show: !i.status,
          },
          {
            label: '编辑',
            icon: 'table_edit',
            has_role: has_role_list.value[1].has_role,
            btn_show: true,
          },
          {
            label: '删除',
            icon: 'table_delete',
            has_role: has_role_list.value[2].has_role,
            btn_show: true,
          },
        ]
      })
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
    })
}
let list_debounce = debounce(200, get_list)
const search_key = () => {
  console.log(header_list.value)
  page_data.value = {
    current: 1,
    pageSize: 10,
    title: header_list.value[0].value,
    type: header_list.value[1].value,
    isSpecScene: header_list.value[2].value,
    sceneType: header_list.value[3].value,
    startTime: header_list.value[4].value,
    endTime: header_list.value[5].value,
    status: header_list.value[6].value,
    maxTimes: header_list.value[7].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    title: '',
    content: '',
    endTime: '',
    jumpUrl: '',
    maxTimes: '',
    noticeReceiveList: [],
    sceneType: '1',
    isSpecScene: true,
    startTime: '',
    status: true,
    type: '1',
    url: [],
  }
  param_list.value = []
  receiveMemberIdList.value = []
  receiveEnterpriseIdList.value = []
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.url_table {
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
</style>
